const Request = require('request');
const Crypto = require('crypto');
const Xml2js = require('xml2js');
const Builder = new Xml2js.Builder({cdata:true});
exports.placeOrder = function (params) {
    return new Promise(function (resolve,reject) {
        let orderObj = {
            appid:config.weChatPay.AppId,//config.weChat.AppID,
            mch_id:config.weChatPay.MerchantNo,
            nonce_str:getRandomString(),
            body:"添加次数充值",
            out_trade_no:params.RechargeTradeNo,
            total_fee:params.RechargeTotalFee * 100,
            spbill_create_ip:params.RechargeCreateIp,
            notify_url:config.weChatPay.NotifyUrl,
            trade_type:'JSAPI',
            openid:params.openid
        };
        orderObj.sign = getSignature(orderObj);
        console.log("==orderObj==",orderObj);
        let orderXml = Builder.buildObject(orderObj);
        console.log('orderXml==>',orderXml);
        Request({
            url: "https://api.mch.weixin.qq.com/pay/unifiedorder",
            headers: {'accept': '*/*', 'cache-control': 'no-cache', 'content-type': 'application/xml'},
            method: "post",
            body:orderXml
        },function (err,response,body) {
            if(err)
                return reject(err);
            Xml2js.parseString(body,{explicitArray:false},function(err,result){
                console.log('parseStr xml==>',result );
                if(err){
                    return reject(err);
                }else{
                    if(result.xml.return_code == 'SUCCESS'&& result.xml.result_code == 'SUCCESS'){
                        resolve(result);
                    }else{
                        reject(result);
                    }
                }
            });
        })
    });
};

function getSignature(params) {
    let keyArray = [];
    let signatureStr = "";
    delete params.sign;
    for (let key in params) {
        keyArray.push(key);
    }
    keyArray.sort();
    for (let i in keyArray) {
        if (params[keyArray[i]] != null) {
            signatureStr += keyArray[i] + "=" + params[keyArray[i]] + "&";
        }
    }
    signatureStr += "key=" + config.weChatPay.PaySecret;
    console.log('signatureStr==>',signatureStr);
    return Crypto.createHash("md5").update(signatureStr,'utf8').digest("hex").toUpperCase();
}
function getRandomString(){
    let chararray = ['1','2','3','4','5','6','7','8','9','0','Q','W','E','R','T','Y','U','I','O','P','L','K','J','H','G','F','D','S','A','Z','X','C','V','B','N','M'];
    let result = "";
    for (let i = 0,l = 32-result.length; i < l; i++) {
        let id = Math.ceil(Math.random() * 35);
        result += chararray[id];
    }
    return result;
}